<?php
function generatePlayChannelImage($img, $play, $target) {
    $info = getimagesize($img);
    $mime = $info['mime'];
    $type = substr(strrchr($mime, '/'), 1);
    $image_types = array('jpeg', 'png', 'gif', 'bmp');
    if (!in_array($type, $image_types)) $type= 'Jpeg';
    $img_create_func = 'ImageCreateFrom' . $type;
    
    $dest = $img_create_func($img);
    $src = imagecreatefromjpeg($play);
    $playW = imagesx($src);
    $playH = imagesy($src);

    $dH = $info[1] - $playH;
    //_play.jpg
    imagecopymerge($dest, $src, 0, $dH, 0, 0, $playW, $playH, 100);
    imagejpeg($dest, $target);
    imagedestroy($dest);
    imagedestroy($src);
}

function cropImage($src, $size, $target = null, $keepBorder = true) {
    if ($target == null) {
        $name = basename($src);
        $pos = strrpos($name, '.');
        $name = ($pos === false) ? $name : substr($name, 0, $pos);
        $target = $name . '_' . implode('x', $size) . '.jpg';
    }
    $info = GetImageSize($src);
    $width = $info[0];
    $height = $info[1];
    /*if ($width == $size[0] && $height == $size[1]) {
        return true;
    }*/


    $mime = $info['mime'];
    $type = substr(strrchr($mime, '/'), 1);
    $image_types = array('jpeg', 'png', 'gif', 'bmp');
    if (!in_array($type, $image_types)) $type= 'Jpeg';


    if ($keepBorder) {
        resizeImage($type, $src, $target, $size[0], $size[1]);
        return true;
    }

    $img_create_func = 'ImageCreateFrom' . $type;
    list($w, $h) = $size;

    $scale_x = $width / $w;
    $scale_y = $height / $h;

    $scale = min($scale_x, $scale_y);
    // Kich thuoc anh crop
    $w *= $scale;
    $h *= $scale;
    $w = intval($w); $h = intval($h);




    $src = $img_create_func($src);
    $dst = ImageCreateTrueColor($w, $h);

    $src_x = ($width - $w)/2;
    $src_y = ($height - $h)/2;

    // Crop
    imagecopy($dst, $src, 0, 0, $src_x, $src_y, $w, $h);

    // Resize
    $res = ImageCreateTrueColor($size[0], $size[1]);
    ImageCopyResampled($res, $dst, 0, 0, 0, 0, $size[0], $size[1], $w, $h);
    imagejpeg($res, $target);//gif give better quatility
    imagedestroy($src);
    imagedestroy($dst);
    return $target;
}

function resizeImage($ext, $tmpname, $target, $xmax, $ymax) {
    $ext = strtolower($ext);

	if($ext == "jpg" || $ext == "jpeg")
		$im = imagecreatefromjpeg($tmpname);
	elseif($ext == "png")
		$im = imagecreatefrompng($tmpname);
	elseif($ext == "gif")
		$im = imagecreatefromgif($tmpname);

	$x = imagesx($im);
	$y = imagesy($im);

	if($x <= $xmax && $y <= $ymax)
		return $im;

	if($x >= $y) {
		$newx = $xmax;
		$newy = $newx * $y / $x;
	}
	else {
		$newy = $ymax;
		$newx = $x / $y * $newy;
	}

	$im2 = imagecreatetruecolor($newx, $newy);
	imagecopyresampled($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);
    imagejpeg($im2, $target);
    imagedestroy($im2);
    imagedestroy($im);
}
